import {
	PATH_IMG,
	BASE_API
} from './config.js'
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import store from '@/store/index.js'

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
Vue.prototype.pathImg = PATH_IMG;
Vue.prototype.baseApi = BASE_API;
// create an axios instance
const service = axios.create({
	baseURL: BASE_API, // url = base url + request url
	//withCredentials: true, // send cookies when cross-domain requests 注意：withCredentials和后端配置的cross跨域不可同时使用
	timeout: 300000, // request timeout
	crossDomain: true
})

// request拦截器,在请求之前做一些处理
service.interceptors.request.use(config => {
		// if (config.method === 'post') {
		// 	config.data = qs.stringify(config.data);
		// }
		if (config.method === 'get') {
			config.url = config.url + "?" + qs.stringify(config.data);
		}
		if (config.method === 'upload') {
			config.method = 'post';
		}
		if (uni.getStorageSync('newToken') && uni.getStorageSync('newToken').overtime) {
			let token = uni.getStorageSync('newToken').token
			let overTimer = null
			let dateTime = new Date().getTime()
			if (uni.getStorageSync('newToken').overtime.toString().length == 10) {
				overTimer = uni.getStorageSync('newToken').overtime * 1000
			} else {
				overTimer = uni.getStorageSync('newToken').overtime
			}
			if (overTimer > dateTime) {
				uni.setStorage({
					key: 'newToken',
					data: {
						token,
						overtime: dateTime + (24 * 60 * 60 * 1000)
					}
				});
				config.headers.common['token'] = token; //从cookie 获取token   传到接口headers里面
			}
		}
		// if (config.url == '/qlyg/cellphone/loginAPi/loginBypwd') {//品牌分类不支持"Content-Type"=="application/x-www-form-urlencoded;charset=UTF-8";
		// 	// config.headers.post["Content-Type"] = 'application/json;charset=UTF-8';
		// 	axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
		// 	console.log(config.headers.post["Content-Type"])
		// }
		// console.log(config)
		return config
	},
	error => {
		console.log(error); // for debug
		return Promise.reject(error);
	}
);


//配置成功后的拦截器
service.interceptors.response.use(response => {
	if (response.status == 200) {
		return Promise.resolve(response);
	} else if (response.status == 401) {
		uni.$u.toast('请先登录');
		store.dispatch("clearIntervalFn");
		if (window) {
			let routerStart = window.location.href.indexOf('pages/')
			let routerEnd = window.location.href.indexOf('?')
			let router = null
			if (routerEnd > 0) {
				router = window.location.href.substring(routerStart, routerEnd)
			} else {
				router = window.location.href.substring(routerStart)
			}
			if (router.includes('AYAYI')) {
				setTimeout(() => {
					uni.clearStorage()
					uni.reLaunch({
						url: '/pages/AYAYI/login'
					})
				}, 1000)
			} else {
				// setTimeout(() => {
					uni.clearStorage()
					uni.reLaunch({
						url: '/pages/login/login'
					})
				// }, 1000)
			}
		} else {
			// setTimeout(() => {
				uni.clearStorage()
				uni.reLaunch({
					url: '/pages/login/login'
				})
			// }, 1000)
		}
	} else {
		return Promise.reject(response);
	}
}, error => {
	if (error.response.status == 401) {
		uni.$u.toast('请先登录');
		store.dispatch("OutLogin");
		store.dispatch("clearIntervalFn");
		if (window) {
			let routerStart = window.location.href.indexOf('pages/')
			let routerEnd = window.location.href.indexOf('?')
			let router = null
			if (routerEnd > 0) {
				router = window.location.href.substring(routerStart, routerEnd)
			} else {
				router = window.location.href.substring(routerStart)
			}
			if (router.includes('AYAYI')) {
				setTimeout(() => {
					uni.clearStorage()
					uni.reLaunch({
						url: '/pages/AYAYI/login'
					})
				}, 1000)
			} else {
				// setTimeout(() => {
					uni.clearStorage()
					uni.reLaunch({
						url: '/pages/login/login'
					})
				// }, 1000)
			}
		} else {
			// setTimeout(() => {
				uni.clearStorage()
				uni.reLaunch({
					url: '/pages/login/login'
				})
			// }, 1000)
		}
	} else if (error.response.status) {
		switch (error.response.status) {
			case 401:
				break;
			default:
				break;
		}
	} else {
		uni.clearStorage()
	}
	return Promise.reject(error)
})

// 在main.js中放入这段自定义适配器的代码，就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求，并支持携带cookie
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			}
		})
	})
}

export default service
